/* gcc -lrt */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <mqueue.h>

#include "msg.h"

int main(int argc, char *argv[])
{
    mqd_t fd;
    mqd_t ret;
    struct mq_attr attr;
    char buf[TEXT_SIZE];
    unsigned prio;
    
    fd = mq_open(argv[1], O_RDONLY, 0444);
    if(fd == -1) {
        ERR_EXIT("consumer: mq_open()");
    } 

    system("cat /dev/mqueue/test");
    int count = 0;
    for(int i =0;i<3;i++){
        //将消息的属性存放在attr中
        if(mq_getattr(fd,&attr)==-1){
            ERR_EXIT("consumer:mq_getattr()");
        }

        //从消息队列中取出消息和优先级.
        ret = mq_receive(fd,buf,attr.mq_msgsize,&prio);
        if(ret==-1){
            ERR_EXIT("consumer:mq_receive()");
        }
        printf("receive %s;priority = %d\n",buf,prio);
        count++;
    }
    system("cat /dev/mqueue/test"); 
    printf("recieve %d messages.\n",count);

    return EXIT_SUCCESS;
}

